/**
 * API请求工具
 * 封装axios请求
 */
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 创建axios实例
const api = axios.create({
  baseURL: process.env.VUE_APP_API_URL || 'http://localhost:8088/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 可以在这里添加认证信息等
    console.log('API Request:', config.method.toUpperCase(), config.url);
    console.log('Request data:', config.data);
    console.log('Request params:', config.params);
    return config;
  },
  error => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  response => {
    console.log('API Response:', response);
    const res = response.data;
    console.log('Response data:', res);

    // 检查是否是包装的响应
    if (res && typeof res.code !== 'undefined') {
      console.log('Wrapped response detected with code:', res.code);
      // 如果是成功的响应
      if (res.code === 200) {
        console.log('Success response, returning data:', res.data);
        return res.data;
      } else {
        // 如果是失败的响应
        console.error('Error response:', res.message);
        ElMessage.error(res.message || '操作失败');
        return Promise.reject(new Error(res.message || '操作失败'));
      }
    }

    // 直接返回数据，Spring Boot默认不会包装响应
    console.log('Unwrapped response, returning directly:', res);
    return res;
  },
  error => {
    console.error('响应错误:', error);
    console.error('Error response:', error.response);
    console.error('Error message:', error.message);
    const message = error.response?.data?.message || '服务器异常';
    ElMessage.error(message);
    return Promise.reject(error);
  }
);

// 课程相关API
export const courseApi = {
  // 获取所有课程
  getAllCourses() {
    return api.get('/courses');
  },

  // 获取课程详情
  getCourse(id) {
    return api.get(`/courses/${id}`);
  },

  // 创建课程
  createCourse(data) {
    return api.post('/courses', data);
  },

  // 更新课程
  updateCourse(id, data) {
    return api.put(`/courses/${id}`, data);
  },

  // 删除课程
  deleteCourse(id) {
    return api.delete(`/courses/${id}`);
  }
};

// 班级相关API
export const classApi = {
  // 获取所有班级
  getAllClasses() {
    return api.get('/classes');
  },

  // 获取班级详情
  getClass(id) {
    return api.get(`/classes/${id}`);
  },

  // 获取课程的班级列表
  getClassesByCourse(courseId) {
    return api.get(`/classes/course/${courseId}`);
  },

  // 创建班级
  createClass(data) {
    return api.post('/classes', data);
  },

  // 更新班级
  updateClass(id, data) {
    return api.put(`/classes/${id}`, data);
  },

  // 删除班级
  deleteClass(id) {
    return api.delete(`/classes/${id}`);
  }
};

// 学生相关API
export const studentApi = {
  // 获取所有学生
  getAllStudents() {
    return api.get('/students');
  },

  // 获取学生详情
  getStudent(id) {
    return api.get(`/students/${id}`);
  },

  // 获取班级的学生列表
  getStudentsByClass(classId) {
    return api.get(`/students/class/${classId}`);
  },

  // 创建学生
  createStudent(data) {
    return api.post('/students', data);
  },

  // 更新学生
  updateStudent(id, data) {
    return api.put(`/students/${id}`, data);
  },

  // 删除学生
  deleteStudent(id) {
    return api.delete(`/students/${id}`);
  },

  // 导入学生
  importStudents(classId, file) {
    const formData = new FormData();
    formData.append('file', file);

    return api.post(`/students/import/${classId}`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  }
};

// 实验相关API
export const experimentApi = {
  // 获取所有实验
  getAllExperiments() {
    return api.get('/experiments');
  },

  // 获取实验详情
  getExperiment(id) {
    return api.get(`/experiments/${id}`);
  },

  // 获取课程的实验列表
  getExperimentsByCourse(courseId) {
    return api.get(`/experiments/course/${courseId}`);
  },

  // 创建实验
  createExperiment(data) {
    return api.post('/experiments', data);
  },

  // 更新实验
  updateExperiment(id, data) {
    return api.put(`/experiments/${id}`, data);
  },

  // 删除实验
  deleteExperiment(id) {
    return api.delete(`/experiments/${id}`);
  },

  // 批量创建实验
  batchCreateExperiments(courseId, count) {
    return api.post(`/experiments/batch?courseId=${courseId}&count=${count}`);
  }
};

// 实验报告相关API
export const reportApi = {
  // 获取学生的实验报告列表
  getReportsByStudent(studentId) {
    return api.get(`/reports/student/${studentId}`);
  },

  // 获取实验的实验报告列表
  getReportsByExperiment(experimentId) {
    return api.get(`/reports/experiment/${experimentId}`);
  },

  // 上传实验报告
  uploadReport(studentId, experimentId, file) {
    const formData = new FormData();
    formData.append('file', file);

    return api.post(`/reports/upload?studentId=${studentId}&experimentId=${experimentId}`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
  },

  // 删除实验报告
  deleteReport(id) {
    return api.delete(`/reports/${id}`);
  },

  // 扫描目录并分析实验报告
  scanAndAnalyzeReports(classId, courseId, directoryPath) {
    return api.post(`/reports/scan?classId=${classId}&courseId=${courseId}&directoryPath=${directoryPath}`);
  },

  // 获取实验维度统计
  getExperimentStatistics(classId, courseId) {
    return api.get(`/reports/statistics/experiment?classId=${classId}&courseId=${courseId}`);
  },

  // 获取学生维度统计
  getStudentStatistics(classId, courseId) {
    return api.get(`/reports/statistics/student?classId=${classId}&courseId=${courseId}`);
  },

  // 获取可视化统计数据
  getVisualizationData(classId, courseId) {
    return api.get(`/reports/statistics/visualization?classId=${classId}&courseId=${courseId}`);
  }
};

export default {
  courseApi,
  classApi,
  studentApi,
  experimentApi,
  reportApi
};
